<template>
  
    <span>
      <el-form :rules="rules" :model="form" ref="form" label-width="120px" >
        <el-form-item label="标题" prop="title">
          
      <el-input v-model="form.title" />
  
    </el-form-item>
    <el-form-item label="内容" prop="content">
      <mavon-editor v-model="form.content" />
    </el-form-item>
    </el-form>
    </span>
 
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="save">
          确定
        </el-button>



</template>
<script>
import axios from 'axios';
import router from '@/router';
export default{
    data(){
        return{
            
            form:{
        title:'',
        content:''
      },
      
      rules: {
        title: [
                    {required: true, message: '请输入标题', trigger: 'blur'}      
        ],
        content: [
                      {required: true, message: '请输入内容', trigger: 'blur'}
                    ]
      }
        }
    },
    created(){
    this.getRouter();
  },
    methods: {
      getRouter(){
        const data = this.$route.query.data;
    if (data) {
      this.form = JSON.parse(data);
    }
      },
        cancel(){
      router.push('/myNews')
    },
        doSave(){
  axios.post('/news/save', JSON.stringify(this.form), {
    headers: {
      'Content-Type': 'application/json'
    }
  }).then(response => { 
    console.log(response.data)
    if(response.data.code == 200){
      this.$message({
        message:'新增成功！正在跳转至资讯页...',
        type: 'success'
      });
      router.push('/myNews')
     
    }else{
      this.$message({
        message:'新增失败，请重试！',
        type: 'error'
      });
    }
  })
},
    doMod(){
      axios.post('/news/update',this.form).then(response=> { 
        console.log(response.data)
        if(response.data.code == 200){
         this.$message({
              message:'修改成功！正在跳转至资讯页...',
              type: 'success'
         });
         router.push('/myNews')
        }else{
          this.$message({
              message:'修改失败，请重试！',
              type: 'error'
         });
        }
      })
    },
    save(){
      this.$refs.form.validate((valid) => {
                    if (valid) {
                      if(this.form.id) {
                        this.doMod();
                      }else{
                        this.doSave();
                      }
                    } else {
                        console.log('error submit!!');
                        return false;
                    }
                });   
    }
    }
}
</script>